package com.czxy.changgou3.config;

import com.czxy.utils.RasUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/22
 */
@Component //让当前类加载到spring容器中
@ConfigurationProperties(prefix = "sc.jwt") //确定自定义key前缀
@Data //get,set
public class JwtProperties {

    private String secret; // 密钥

    private String pubKeyPath;// 公钥

    private String priKeyPath;// 私钥

    private int expire;// token过期时间

    //公钥/私钥的路径  --> 对象

    private PublicKey publicKey; // 公钥对象

    private PrivateKey privateKey; // 私钥对象

    @PostConstruct
    public void init(){
        try {
            //1 将公钥/私钥 路径 --> 文件对象
            File pubFile = new File(this.pubKeyPath);
            File PriFile = new File(this.priKeyPath);
            //2 校验文件,不存在生产公钥和私钥
            if (!pubFile.exists() || !PriFile.exists()){
                RasUtils.generateKey(this.pubKeyPath,this.priKeyPath,this.secret);
            }
            //文件对象 --》公钥/私钥 对象
            this.publicKey = RasUtils.getPublicKey(this.pubKeyPath);
            this.privateKey = RasUtils.getPrivateKey(this.priKeyPath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
